﻿using h2sbk_sharp.DoNetExt;
using H2SDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace h2sbk_sharp.Controllers
{
    public class PointController : ApiController
    {
        class allresult
        {
            public int terminalid { set; get; }
            public int pointid { set; get; }
            public string address { set; get; }
            public string person { set; get; }
        }
        [HttpGet, HttpPost]
        public HttpResponseMessage all()
        {
            using (h2sDataContext db = new h2sDataContext())
            {
                string sqlCmd = @"
                    select
	                    b.id as 'terminalid',
	                    a.id as 'pointid',
	                    a.address as 'address',
	                    c.realname as 'person'
                    from
	                    point a
	                    left join
	                    terminal b
                    on
	                    a.terminalid = b.id
	                    left join
	                    [user] c
                    on
	                    b.userid = c.id
                ";
                var result = db.ExecuteQuery<allresult>(sqlCmd).ToArray();
                return result.ToHttpResponseMessage();
            }
        }
        [HttpGet, HttpPost]
        public HttpResponseMessage setaddress(int id, int terminalid, string address)
        {
            string rtv = null;
            try
            {
                using (h2sDataContext db = new h2sDataContext())
                {
                    var point = db.point.Where(p => p.id == id && p.terminalid == terminalid).FirstOrDefault();
                    if (point != null)
                    {
                        point.address = address;
                        db.SubmitChanges();
                        rtv = "ok";
                    }
                    else
                    {
                        rtv = "该采集点不存在";
                    }
                }
            }
            catch (Exception e)
            {
                rtv = e.Message;
            }
            return rtv.ToHttpResponseMessage();
        }
        [HttpGet, HttpPost]
        public HttpResponseMessage newcount ()
        {
            int count;
            using (h2sDataContext db = new h2sDataContext())
            {
                count = db.point.Where(p => p.address == null || p.address.Trim().Length == 0).Count();
            }
            return count.ToHttpResponseMessage();
        }

        [HttpGet, HttpPost]
        public HttpResponseMessage allid(int terminalid)
        {
            using (h2sDataContext db = new h2sDataContext())
            {
                return db.allPoint(terminalid).ToHttpResponseMessage();
            }
        }
    }
}
